<?php
require_once __DIR__ . '/../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问此页面', 'danger');
}

// 获取系统设置
$db = getDB();
$settings = [];
$stmt = $db->query("SELECT * FROM settings");
foreach ($stmt->fetchAll() as $setting) {
    $settings[$setting['key_name']] = $setting['key_value'];
}

$expressBalance = isset($settings['express_balance']) && $settings['express_balance'] !== '' 
    ? floatval($settings['express_balance']) 
    : 0.00;

include __DIR__ . '/header.php';
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">快递查询工具</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button type="button" class="btn btn-sm btn-outline-info" onclick="checkExpressBalance()">
                <i class="bi bi-arrow-repeat"></i> 更新余额
            </button>
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearAllStoredData()">
                <i class="bi bi-trash"></i> 清除数据
            </button>
        </div>
    </div>
</div>

<!-- 余额显示 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card border-left-info">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            快递查询余额
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="expressBalanceDisplay">
                            ¥<?php echo number_format($expressBalance, 2); ?>
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-wallet2 fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 查询区域 -->
<div class="card mb-4">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="bi bi-search"></i> 快递查询
        </h5>
    </div>
    <div class="card-body">
        <form id="expressQueryForm">
            <div class="row mb-3">
                <div class="col-md-8">
                    <label for="trackingNumbers" class="form-label">快递单号</label>
                    <textarea class="form-control" id="trackingNumbers" name="tracking_numbers" 
                              rows="6" placeholder="请输入快递单号，每行一个单号&#10;例如：&#10;SF1234567890&#10;YT1234567890"></textarea>
                    <div class="form-text">每行输入一个快递单号，支持批量查询</div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="sfPhoneTail" class="form-label">顺丰手机尾号（后4位）</label>
                        <input type="text" class="form-control" id="sfPhoneTail" name="sf_phone_tail"
                               maxlength="4" pattern="[0-9]{4}" 
                               value="<?php echo htmlspecialchars($settings['sf_phone_tail'] ?? ''); ?>"
                               placeholder="请输入顺丰手机尾号">
                        <div class="form-text">查询顺丰快递时需要</div>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-outline-secondary" onclick="importTrackingNumbers()">
                            <i class="bi bi-upload"></i> 导入单号
                        </button>
                        
                        <button type="button" class="btn btn-outline-primary" onclick="exportTrackingNumbers()">
                            <i class="bi bi-download"></i> 导出单号
                        </button>
                        
                        <button type="button" class="btn btn-outline-warning" onclick="clearTrackingNumbers()">
                            <i class="bi bi-trash"></i> 清空单号
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-12">
                    <div class="d-flex justify-content-between">
                        <div>
                            <span id="trackingCount" class="text-muted">0 个单号</span>
                        </div>
                        <div>
                            <button type="button" class="btn btn-primary" onclick="startQuery()" id="queryBtn">
                                <i class="bi bi-search"></i> 开始查询
                            </button>
                            <button type="button" class="btn btn-secondary" onclick="stopQuery()" id="stopBtn" style="display: none;">
                                <i class="bi bi-stop-circle"></i> 停止查询
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 查询进度 -->
<div class="card mb-4" id="progressCard" style="display: none;">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="bi bi-graph-up"></i> 查询进度
        </h5>
    </div>
    <div class="card-body">
        <div class="progress mb-3">
            <div class="progress-bar progress-bar-striped progress-bar-animated" 
                 id="progressBar" role="progressbar" style="width: 0%"></div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <small>总单号: <span id="totalCount">0</span></small>
            </div>
            <div class="col-md-4">
                <small>已完成: <span id="completedCount">0</span></small>
            </div>
            <div class="col-md-4">
                <small>成功率: <span id="successRate">0%</span></small>
            </div>
        </div>
        <div class="mt-2">
            <small id="currentTracking" class="text-muted">准备开始查询...</small>
        </div>
    </div>
</div>

<!-- 查询结果 -->
<div class="card" id="resultCard" style="display: none;">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="bi bi-list-check"></i> 查询结果
        </h5>
        <div>
            <button type="button" class="btn btn-sm btn-outline-success" onclick="exportSelectedResults()">
                <i class="bi bi-download"></i> 导出选中
            </button>
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="exportAllResults()">
                <i class="bi bi-download"></i> 导出全部
            </button>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover" id="resultTable">
                <thead>
                    <tr>
                        <th width="30">
                            <input type="checkbox" id="selectAllResults" onchange="toggleAllResults()">
                        </th>
                        <th>单号</th>
                        <th>物流信息</th>
                        <th>最新时间</th>
                        <th>当前所在地</th>
                        <th>快递公司</th>
                        <th>运输时长</th>
                        <th>是否签收</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="resultBody">
                    <!-- 结果将通过JavaScript动态添加 -->
                </tbody>
            </table>
        </div>
        
        <div class="text-center mt-3" id="noResults" style="display: none;">
            <i class="bi bi-inbox display-4 text-muted"></i>
            <p class="text-muted mt-2">暂无查询结果</p>
        </div>
    </div>
</div>

<!-- 物流详情模态框 -->
<div class="modal fade" id="trackingDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">物流详情 - <span id="modalTrackingNo"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="trackingDetailContent">
                <!-- 详情内容将通过JavaScript动态添加 -->
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>

<script>
// 全局变量
let isQueryRunning = false;
let currentQueryIndex = 0;
let trackingNumbers = [];
let queryResults = [];
let stopRequested = false;
let batchMode = false;

// localStorage 键名
const STORAGE_KEYS = {
    QUERY_RESULTS: 'express_tool_query_results',
    TRACKING_NUMBERS: 'express_tool_tracking_numbers',
    QUERY_STATE: 'express_tool_query_state'
};

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    updateTrackingCount();
    
    // 监听输入变化
    document.getElementById('trackingNumbers').addEventListener('input', updateTrackingCount);
    
    // 恢复上次的查询结果
    restoreQueryData();
});

// 保存查询数据到 localStorage
function saveQueryData() {
    try {
        const dataToSave = {
            queryResults: queryResults,
            trackingNumbers: trackingNumbers,
            timestamp: new Date().getTime()
        };
        
        localStorage.setItem(STORAGE_KEYS.QUERY_RESULTS, JSON.stringify(dataToSave));
        localStorage.setItem(STORAGE_KEYS.TRACKING_NUMBERS, document.getElementById('trackingNumbers').value);
        
        const queryState = {
            isQueryRunning: isQueryRunning,
            currentQueryIndex: currentQueryIndex,
            stopRequested: stopRequested,
            batchMode: batchMode,
            timestamp: new Date().getTime()
        };
        localStorage.setItem(STORAGE_KEYS.QUERY_STATE, JSON.stringify(queryState));
        
    } catch (e) {
        console.error('保存数据失败:', e);
    }
}

// 恢复查询数据
function restoreQueryData() {
    try {
        // 恢复单号列表
        const savedNumbers = localStorage.getItem(STORAGE_KEYS.TRACKING_NUMBERS);
        if (savedNumbers) {
            document.getElementById('trackingNumbers').value = savedNumbers;
            updateTrackingCount();
        }
        
        // 恢复查询结果
        const savedResults = localStorage.getItem(STORAGE_KEYS.QUERY_RESULTS);
        if (savedResults) {
            const data = JSON.parse(savedResults);
            const now = new Date().getTime();
            const oneDay = 24 * 60 * 60 * 1000;
            
            if (now - data.timestamp < oneDay) {
                queryResults = data.queryResults || [];
                trackingNumbers = data.trackingNumbers || [];
                
                if (queryResults.length > 0) {
                    restoreResultsToTable();
                    showToast('已恢复上次的查询结果', 'info');
                }
            } else {
                clearStoredData();
            }
        }
        
        // 恢复查询状态
        const savedState = localStorage.getItem(STORAGE_KEYS.QUERY_STATE);
        if (savedState) {
            const state = JSON.parse(savedState);
            const now = new Date().getTime();
            const thirtyMinutes = 30 * 60 * 1000;
            
            if (now - state.timestamp < thirtyMinutes && state.isQueryRunning) {
                batchMode = state.batchMode || false;
                showQueryRecoveryOption();
            }
        }
        
    } catch (e) {
        console.error('恢复数据失败:', e);
        clearStoredData();
    }
}

// 恢复结果显示到表格
function restoreResultsToTable() {
    const tbody = document.getElementById('resultBody');
    const noResults = document.getElementById('noResults');
    
    tbody.innerHTML = '';
    
    if (queryResults.length === 0) {
        noResults.style.display = 'block';
        document.getElementById('resultCard').style.display = 'none';
        return;
    }
    
    noResults.style.display = 'none';
    document.getElementById('resultCard').style.display = 'block';
    
    queryResults.forEach(result => {
        addResultToTable(result, false);
    });
    
    updateStatistics();
}

// 更新统计信息
function updateStatistics() {
    const successCount = queryResults.filter(r => r.success).length;
    const totalCount = queryResults.length;
    const successRate = totalCount > 0 ? Math.round((successCount / totalCount) * 100) : 0;
    
    document.getElementById('totalCount').textContent = totalCount;
    document.getElementById('completedCount').textContent = totalCount;
    document.getElementById('successRate').textContent = successRate + '%';
    document.getElementById('progressBar').style.width = '100%';
}

// 显示查询恢复选项
function showQueryRecoveryOption() {
    const modeText = batchMode ? '批量' : '单个';
    const recoveryHtml = `
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            <i class="bi bi-exclamation-triangle"></i>
            <strong>检测到未完成的${modeText}查询</strong>
            <p class="mb-2">上次的查询被中断，您可以选择：</p>
            <div class="btn-group btn-group-sm">
                <button type="button" class="btn btn-outline-primary" onclick="recoverLastQuery()">
                    <i class="bi bi-arrow-clockwise"></i> 恢复查询
                </button>
                <button type="button" class="btn btn-outline-secondary" onclick="clearQueryState()">
                    <i class="bi bi-x-circle"></i> 清除状态
                </button>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    document.querySelector('.container-fluid').insertAdjacentHTML('afterbegin', recoveryHtml);
}

// 恢复上次查询
function recoverLastQuery() {
    const savedState = localStorage.getItem(STORAGE_KEYS.QUERY_STATE);
    if (savedState) {
        const state = JSON.parse(savedState);
        
        document.getElementById('progressCard').style.display = 'block';
        document.getElementById('resultCard').style.display = 'block';
        document.getElementById('queryBtn').style.display = 'none';
        document.getElementById('stopBtn').style.display = 'inline-block';
        
        isQueryRunning = true;
        currentQueryIndex = state.currentQueryIndex;
        stopRequested = false;
        batchMode = state.batchMode || false;
        
        if (batchMode) {
            batchQueryNext();
        } else {
            queryNext();
        }
        
        showToast('已恢复查询', 'success');
    }
}

// 清除查询状态
function clearQueryState() {
    localStorage.removeItem(STORAGE_KEYS.QUERY_STATE);
    showToast('已清除查询状态', 'info');
}

// 清除存储的数据
function clearStoredData() {
    localStorage.removeItem(STORAGE_KEYS.QUERY_RESULTS);
    localStorage.removeItem(STORAGE_KEYS.TRACKING_NUMBERS);
    localStorage.removeItem(STORAGE_KEYS.QUERY_STATE);
}

// 更新单号计数
function updateTrackingCount() {
    const textarea = document.getElementById('trackingNumbers');
    const numbers = textarea.value.split('\n').filter(num => num.trim() !== '');
    document.getElementById('trackingCount').textContent = numbers.length + ' 个单号';
    
    saveQueryData();
}

// 导入单号文件 - 使用后端导入
function importTrackingNumbers() {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.txt,.csv,.xls,.xlsx';
    fileInput.style.display = 'none';
    
    fileInput.onchange = function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        showToast('正在导入文件...', 'info');
        
        const formData = new FormData();
        formData.append('action', 'import_tracking_numbers');
        formData.append('file', file);
        
        fetch('api/express_tool_api.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const numbers = data.data;
                const textarea = document.getElementById('trackingNumbers');
                
                // 获取现有单号
                const existingNumbers = textarea.value.split('\n')
                    .map(num => num.trim())
                    .filter(num => num !== '');
                
                // 合并并去重
                const allNumbers = [...new Set([...existingNumbers, ...numbers])];
                textarea.value = allNumbers.join('\n');
                
                updateTrackingCount();
                showToast(data.message, 'success');
            } else {
                showToast('导入失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showToast('导入失败: ' + error.message, 'danger');
        })
        .finally(() => {
            document.body.removeChild(fileInput);
        });
    };
    
    document.body.appendChild(fileInput);
    fileInput.click();
}

// 导出单号
function exportTrackingNumbers() {
    const numbers = document.getElementById('trackingNumbers').value
        .split('\n')
        .filter(num => num.trim() !== '');
    
    if (numbers.length === 0) {
        showToast('没有可导出的单号', 'warning');
        return;
    }
    
    showExportFormatModal(numbers, '单号');
}

// 导出结果
function exportSelectedResults() {
    const selectedCheckboxes = document.querySelectorAll('.result-checkbox:checked');
    if (selectedCheckboxes.length === 0) {
        showToast('请先选择要导出的结果', 'warning');
        return;
    }
    
    const selectedNumbers = Array.from(selectedCheckboxes).map(cb => cb.value);
    const selectedResults = queryResults.filter(r => selectedNumbers.includes(r.trackingNo));
    
    showExportFormatModal(selectedResults, '结果', true);
}

function exportAllResults() {
    if (queryResults.length === 0) {
        showToast('没有可导出的结果', 'warning');
        return;
    }
    
    showExportFormatModal(queryResults, '结果', true);
}

// 显示导出格式选择模态框
function showExportFormatModal(data, type, isResults = false) {
    const modalHtml = `
        <div class="modal fade" id="exportFormatModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">选择导出格式</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="list-group">
                            <button type="button" class="list-group-item list-group-item-action" onclick="exportData('txt', ${isResults})">
                                <i class="bi bi-file-earmark-text"></i> TXT 文本文件
                            </button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="exportData('csv', ${isResults})">
                                <i class="bi bi-file-earmark-spreadsheet"></i> CSV 表格文件
                            </button>
                        </div>
                        <div class="mt-3">
                            <small class="text-muted">即将导出 ${data.length} 条${type}</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    window.exportDataCache = {
        data: data,
        type: type,
        isResults: isResults
    };
    
    const modal = new bootstrap.Modal(document.getElementById('exportFormatModal'));
    modal.show();
    
    document.getElementById('exportFormatModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
        delete window.exportDataCache;
    });
}

// 执行导出
function exportData(format, isResults) {
    if (!window.exportDataCache) return;
    
    const { data, type, isResults: isResultsData } = window.exportDataCache;
    
    try {
        switch (format) {
            case 'txt':
                exportToTxt(data, isResultsData);
                break;
            case 'csv':
                exportToCsv(data, isResultsData);
                break;
            default:
                throw new Error('不支持的导出格式: ' + format);
        }
        
        const modal = bootstrap.Modal.getInstance(document.getElementById('exportFormatModal'));
        if (modal) modal.hide();
        
        showToast(`成功导出 ${data.length} 条${type}`, 'success');
    } catch (error) {
        console.error('导出失败:', error);
        showToast('导出失败: ' + error.message, 'danger');
    }
}

// 导出为TXT
function exportToTxt(data, isResults) {
    let content = '';
    
    if (isResults) {
        data.forEach(result => {
            if (result.success && result.data) {
                content += `${result.trackingNo}\t${result.data.express_company}\t${result.data.latest_status}\t${result.data.is_signed ? '已签收' : '运输中'}\n`;
            } else {
                content += `${result.trackingNo}\t查询失败\t${result.message}\n`;
            }
        });
    } else {
        content = data.join('\n');
    }
    
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    downloadFile(blob, `快递${isResults ? '查询结果' : '单号'}_${getTimestamp()}.txt`);
}

// 导出为CSV
function exportToCsv(data, isResults) {
    let csvContent = '';
    
    if (isResults) {
        csvContent = '单号,快递公司,物流信息,最新时间,当前所在地,运输时长,是否签收,状态\n';
        
        data.forEach(result => {
            const row = [
                result.trackingNo,
                result.success ? (result.data.express_company || '-') : '-',
                result.success ? (result.data.latest_status || '-') : '查询失败',
                result.success ? (result.data.latest_time || '-') : '-',
                result.success ? (result.data.current_location || '-') : '-',
                result.success ? (result.data.transport_time || '-') : '-',
                result.success ? (result.data.is_signed ? '已签收' : '运输中') : '-',
                result.success ? '成功' : '失败'
            ].map(field => `"${field}"`).join(',');
            
            csvContent += row + '\n';
        });
    } else {
        csvContent = '快递单号\n' + data.join('\n');
    }
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' });
    downloadFile(blob, `快递${isResults ? '查询结果' : '单号'}_${getTimestamp()}.csv`);
}

// 通用文件下载函数
function downloadFile(blob, filename) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// 获取时间戳
function getTimestamp() {
    return new Date().toLocaleDateString('zh-CN').replace(/\//g, '-') + '_' + 
           new Date().toTimeString().split(' ')[0].replace(/:/g, '-');
}

// 清空单号
function clearTrackingNumbers() {
    if (confirm('确定要清空所有单号吗？')) {
        document.getElementById('trackingNumbers').value = '';
        updateTrackingCount();
    }
}

// 开始查询
function startQuery() {
    const textarea = document.getElementById('trackingNumbers');
    const numbers = textarea.value.split('\n')
        .map(num => num.trim())
        .filter(num => num !== '');
    
    if (numbers.length === 0) {
        showToast('请输入至少一个快递单号', 'warning');
        return;
    }
    
    if (numbers.length > 1) {
        showQueryModeModal(numbers);
    } else {
        startSingleQuery(numbers);
    }
}

// 显示查询模式选择模态框
function showQueryModeModal(numbers) {
    const modalHtml = `
        <div class="modal fade" id="queryModeModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">选择查询模式</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p>检测到 <strong>${numbers.length}</strong> 个快递单号，请选择查询模式：</p>
                        <div class="list-group">
                            <button type="button" class="list-group-item list-group-item-action" onclick="startBatchQuery(${JSON.stringify(numbers).replace(/"/g, '&quot;')})">
                                <div class="d-flex w-100 justify-content-between">
                                    <h6 class="mb-1"><i class="bi bi-lightning-fill text-warning"></i> 批量快速查询</h6>
                                </div>
                                <p class="mb-1">一次性查询所有单号，速度更快</p>
                                <small class="text-muted">推荐用于大量单号查询</small>
                            </button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="startSingleQuery(${JSON.stringify(numbers).replace(/"/g, '&quot;')})">
                                <div class="d-flex w-100 justify-content-between">
                                    <h6 class="mb-1"><i class="bi bi-arrow-right-circle text-primary"></i> 单个顺序查询</h6>
                                </div>
                                <p class="mb-1">逐个查询单号，稳定性更好</p>
                                <small class="text-muted">适合少量单号或网络不稳定时</small>
                            </button>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    const modal = new bootstrap.Modal(document.getElementById('queryModeModal'));
    modal.show();
    
    document.getElementById('queryModeModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

// 开始单个查询
function startSingleQuery(numbers) {
    isQueryRunning = true;
    stopRequested = false;
    currentQueryIndex = 0;
    trackingNumbers = numbers;
    queryResults = [];
    batchMode = false;
    
    updateQueryUI();
    saveQueryData();
    queryNext();
}

// 开始批量查询
function startBatchQuery(numbers) {
    isQueryRunning = true;
    stopRequested = false;
    currentQueryIndex = 0;
    trackingNumbers = numbers;
    queryResults = [];
    batchMode = true;
    
    updateQueryUI();
    saveQueryData();
    batchQueryNext();
}

// 更新查询UI
function updateQueryUI() {
    document.getElementById('queryBtn').style.display = 'none';
    document.getElementById('stopBtn').style.display = 'inline-block';
    document.getElementById('progressCard').style.display = 'block';
    document.getElementById('resultCard').style.display = 'block';
    
    document.getElementById('totalCount').textContent = trackingNumbers.length;
    document.getElementById('completedCount').textContent = '0';
    document.getElementById('successRate').textContent = '0%';
    document.getElementById('progressBar').style.width = '0%';
    document.getElementById('resultBody').innerHTML = '';
    document.getElementById('noResults').style.display = 'none';
    
    const modeText = batchMode ? '批量' : '单个';
    document.getElementById('currentTracking').textContent = `准备开始${modeText}查询...`;
}

// 停止查询
function stopQuery() {
    stopRequested = true;
    isQueryRunning = false;
    document.getElementById('stopBtn').style.display = 'none';
    document.getElementById('queryBtn').style.display = 'inline-block';
    
    saveQueryData();
    showToast('查询已停止', 'info');
}

// 单个查询下一个单号
function queryNext() {
    if (stopRequested || currentQueryIndex >= trackingNumbers.length) {
        finishQuery();
        return;
    }
    
    const trackingNo = trackingNumbers[currentQueryIndex];
    const sfPhoneTail = document.getElementById('sfPhoneTail').value;
    
    document.getElementById('currentTracking').textContent = `正在查询: ${trackingNo} (${currentQueryIndex + 1}/${trackingNumbers.length})`;
    
    querySingleTracking(trackingNo, sfPhoneTail);
}

// 批量查询
function batchQueryNext() {
    if (stopRequested) {
        finishQuery();
        return;
    }
    
    const sfPhoneTail = document.getElementById('sfPhoneTail').value;
    
    document.getElementById('currentTracking').textContent = `正在批量查询 ${trackingNumbers.length} 个单号...`;
    
    batchQueryTracking(trackingNumbers, sfPhoneTail);
}

// 批量查询快递
function batchQueryTracking(trackingNumbers, sfPhoneTail) {
    const formData = new FormData();
    formData.append('action', 'batch_query_tool');
    formData.append('tracking_numbers', JSON.stringify(trackingNumbers));
    if (sfPhoneTail) {
        formData.append('sf_phone_tail', sfPhoneTail);
    }
    
    fetch('api/express_tool_api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            data.data.results.forEach(result => {
                processQueryResult(result.trackingNo, {
                    success: result.success,
                    data: result.data,
                    message: result.message
                });
            });
            
            currentQueryIndex = trackingNumbers.length;
            updateProgress();
            finishQuery();
            
        } else {
            showToast('批量查询失败，转为单个查询: ' + data.message, 'warning');
            batchMode = false;
            queryNext();
        }
    })
    .catch(error => {
        showToast('批量查询请求失败，转为单个查询: ' + error.message, 'warning');
        batchMode = false;
        queryNext();
    });
}

// 查询单个快递
function querySingleTracking(trackingNo, sfPhoneTail) {
    const formData = new FormData();
    formData.append('action', 'query_tool');
    formData.append('tracking_no', trackingNo);
    if (sfPhoneTail) {
        formData.append('sf_phone_tail', sfPhoneTail);
    }
    
    fetch('api/express_tool_api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        processQueryResult(trackingNo, data);
        
        currentQueryIndex++;
        updateProgress();
        
        if (!batchMode) {
            setTimeout(queryNext, 500);
        }
    })
    .catch(error => {
        processQueryResult(trackingNo, {
            success: false,
            message: '请求失败: ' + error.message
        });
        
        currentQueryIndex++;
        updateProgress();
        
        if (!batchMode) {
            setTimeout(queryNext, 500);
        }
    });
}

// 处理查询结果
function processQueryResult(trackingNo, result) {
    const resultItem = {
        trackingNo: trackingNo,
        success: result.success,
        data: result.data || {},
        message: result.message || '',
        timestamp: new Date().getTime()
    };
    
    queryResults.push(resultItem);
    addResultToTable(resultItem);
    
    saveQueryData();
}

// 更新进度
function updateProgress() {
    const progress = (currentQueryIndex / trackingNumbers.length) * 100;
    document.getElementById('progressBar').style.width = progress + '%';
    document.getElementById('completedCount').textContent = currentQueryIndex;
    
    const successCount = queryResults.filter(r => r.success).length;
    const successRate = trackingNumbers.length > 0 ? 
        Math.round((successCount / trackingNumbers.length) * 100) : 0;
    document.getElementById('successRate').textContent = successRate + '%';
    
    const queryState = {
        isQueryRunning: isQueryRunning,
        currentQueryIndex: currentQueryIndex,
        stopRequested: stopRequested,
        batchMode: batchMode,
        timestamp: new Date().getTime()
    };
    localStorage.setItem(STORAGE_KEYS.QUERY_STATE, JSON.stringify(queryState));
}

// 完成查询
function finishQuery() {
    isQueryRunning = false;
    document.getElementById('stopBtn').style.display = 'none';
    document.getElementById('queryBtn').style.display = 'inline-block';
    
    const queryState = {
        isQueryRunning: false,
        currentQueryIndex: currentQueryIndex,
        stopRequested: stopRequested,
        batchMode: batchMode,
        timestamp: new Date().getTime()
    };
    localStorage.setItem(STORAGE_KEYS.QUERY_STATE, JSON.stringify(queryState));
    
    if (currentQueryIndex >= trackingNumbers.length) {
        const modeText = batchMode ? '批量' : '单个';
        showToast(`${modeText}查询完成`, 'success');
        
        // 只在所有查询完成后更新余额
        updateBalanceAfterQuery();
    }
}

// 添加结果到表格
function addResultToTable(result, saveData = true) {
    const tbody = document.getElementById('resultBody');
    const noResults = document.getElementById('noResults');
    
    if (tbody.children.length === 0) {
        noResults.style.display = 'none';
        document.getElementById('resultCard').style.display = 'block';
    }
    
    const row = document.createElement('tr');
    
    let logisticsInfo = '-';
    let latestTime = '-';
    let currentLocation = '-';
    let expressCompany = '-';
    let transportTime = '-';
    let isSigned = '-';
    
    if (result.success && result.data) {
        const data = result.data;
        logisticsInfo = data.latest_status || '-';
        latestTime = data.latest_time || '-';
        currentLocation = data.current_location || '-';
        expressCompany = data.express_company || '-';
        transportTime = data.transport_time || '-';
        isSigned = data.is_signed ? 
            '<span class="badge bg-success">已签收</span>' : 
            '<span class="badge bg-warning">运输中</span>';
    }
    
    row.innerHTML = `
        <td>
            <input type="checkbox" class="result-checkbox" value="${result.trackingNo}">
        </td>
        <td>${result.trackingNo}</td>
        <td>${logisticsInfo}</td>
        <td>${latestTime}</td>
        <td>${currentLocation}</td>
        <td>${expressCompany}</td>
        <td>${transportTime}</td>
        <td>${isSigned}</td>
        <td>
            <button type="button" class="btn btn-sm btn-outline-info" 
                    onclick="showTrackingDetail('${result.trackingNo}')"
                    ${!result.success ? 'disabled' : ''}>
                <i class="bi bi-eye"></i> 详情
            </button>
        </td>
    `;
    
    if (!result.success) {
        row.classList.add('table-danger');
    } else if (result.data && result.data.is_signed) {
        row.classList.add('table-success');
    }
    
    tbody.appendChild(row);
    
    if (saveData) {
        saveQueryData();
    }
}

// 显示物流详情
function showTrackingDetail(trackingNo) {
    const result = queryResults.find(r => r.trackingNo === trackingNo);
    if (!result || !result.success) return;
    
    document.getElementById('modalTrackingNo').textContent = trackingNo;
    
    let content = '';
    if (result.data && result.data.tracking_list && result.data.tracking_list.length > 0) {
        content = `
            <div class="tracking-timeline">
                ${result.data.tracking_list.map(item => `
                    <div class="tracking-item ${item.is_latest ? 'latest' : ''}">
                        <div class="tracking-time">${item.time}</div>
                        <div class="tracking-status">${item.status}</div>
                        ${item.location ? `<div class="tracking-location text-muted">${item.location}</div>` : ''}
                    </div>
                `).join('')}
            </div>
        `;
    } else {
        content = `
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i> 
                <strong>物流信息</strong>
                <p class="mb-1">快递公司：${result.data.express_company || '未知'}</p>
                <p class="mb-1">最新状态：${result.data.latest_status || '暂无信息'}</p>
                <p class="mb-0">更新时间：${result.data.update_time || '未知'}</p>
            </div>
        `;
    }
    
    document.getElementById('trackingDetailContent').innerHTML = content;
    
    const modal = new bootstrap.Modal(document.getElementById('trackingDetailModal'));
    modal.show();
}

// 全选/取消全选结果
function toggleAllResults() {
    const selectAll = document.getElementById('selectAllResults').checked;
    const checkboxes = document.querySelectorAll('.result-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll;
    });
}

// 查询完成后更新余额
function updateBalanceAfterQuery() {
    fetch('api/express_query.php?action=check_balance')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('expressBalanceDisplay').textContent = '¥' + parseFloat(data.balance).toFixed(2);
                showToast(`余额已更新: ¥${data.balance}`, 'success');
            } else {
                showToast('余额更新失败: ' + data.message, 'warning');
            }
        })
        .catch(error => {
            console.error('余额更新失败:', error);
        });
}

// 检查余额
function checkExpressBalance() {
    fetch('api/express_query.php?action=check_balance')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('expressBalanceDisplay').textContent = '¥' + parseFloat(data.balance).toFixed(2);
                showToast(`当前余额: ¥${data.balance}`, 'success');
            } else {
                showToast('余额查询失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showToast('请求失败: ' + error.message, 'danger');
        });
}

// 清除所有存储的数据
function clearAllStoredData() {
    if (confirm('确定要清除所有存储的查询数据吗？这将删除所有查询结果和单号列表。')) {
        clearStoredData();
        queryResults = [];
        trackingNumbers = [];
        document.getElementById('trackingNumbers').value = '';
        document.getElementById('resultBody').innerHTML = '';
        document.getElementById('resultCard').style.display = 'none';
        document.getElementById('progressCard').style.display = 'none';
        updateTrackingCount();
        showToast('已清除所有存储数据', 'success');
    }
}

// 简单的提示函数
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type === 'success' ? 'success' : type === 'warning' ? 'warning' : type === 'danger' ? 'danger' : 'info'} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    toastContainer.appendChild(toast);
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}

function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed top-0 end-0 p-3';
    container.style.zIndex = '9999';
    document.body.appendChild(container);
    return container;
}

// 防止页面刷新重复提交
window.addEventListener('beforeunload', function(e) {
    if (isQueryRunning) {
        e.preventDefault();
        e.returnValue = '查询正在进行中，确定要离开吗？';
        return e.returnValue;
    }
});
</script>

<style>
.tracking-timeline {
    position: relative;
    padding-left: 20px;
    border-left: 2px solid #e9ecef;
    max-height: 400px;
    overflow-y: auto;
}

.tracking-item {
    position: relative;
    padding: 10px 0;
    margin-left: 20px;
}

.tracking-item::before {
    content: '';
    position: absolute;
    left: -30px;
    top: 15px;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #6c757d;
    border: 2px solid white;
}

.tracking-item.latest::before {
    background: #28a745;
    box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.2);
}

.tracking-time {
    font-size: 0.875rem;
    color: #6c757d;
    margin-bottom: 5px;
}

.tracking-status {
    font-size: 0.9rem;
    color: #495057;
    margin-bottom: 3px;
}

.tracking-location {
    font-size: 0.8rem;
}

.progress-bar-animated {
    animation: progress-bar-stripes 1s linear infinite;
}

@keyframes progress-bar-stripes {
    0% { background-position: 1rem 0; }
    100% { background-position: 0 0; }
}
</style>